{{define "tree.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Preview System</title>
    <style>
        /* 分栏布局 */
        .container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        /* 左侧目录树 */
        .tree-panel {
            width: 350px;
            border-right: 1px solid #ccc;
            overflow-y: auto;
            padding: 15px;
            background: #f8f9fa;
        }

        /* 右侧预览区 */
        .preview-panel {
            flex: 1;
            position: relative;
        }

        #preview-frame {
            width: 100%;
            height: 100%;
            border: none;
        }

        /* 加载提示 */
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: none;
            align-items: center;
            justify-content: center;
            font-size: 1.2em;
            color: #666;
        }

        /* 目录树样式（保持原有样式优化） */
        .tree { 
            font-family: 'Menlo', 'Consolas', monospace; 
        }
        details { 
            margin-left: 0.1em; 
             /* 去除默认的展开箭头 */
            list-style-type: none; 
        }
        summary {
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: background 0.2s;
            /* 确保和文件项左右对齐 */
            display: inline-block;
            margin-left: -1.2em;
        }
        summary:hover { background: #e9ecef; }
        .file {
            cursor: pointer;
            padding: 4px 8px;
            transition: all 0.2s;
            border-radius: 4px;
            margin-left: -1.2em;  /* 新增：与summary的负边距保持一致 */
        }
        .file:hover { background: #e9ecef; }
        .folder::before { content: '📁'; }
        .file::before { content: '📄'; }
        [data-status="loading"] { opacity: 0.5; }
        [data-status="loaded"] { color: #2c7a2c; }
        /* 新增样式类 */
        .covered-70 {
            background-color: lightgreen;
        }
        .covered-less-70 {
            background-color: lightcoral;
        }
        ul {
            padding-left: 0.6em;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧目录树 -->
        <div class="tree-panel">
            <div id="tree-container" class="tree"></div>
        </div>

        <!-- 右侧预览区 -->
        <div class="preview-panel">
            <div id="loading" class="loading-overlay">Loading...</div>
            <iframe id="preview-frame"></iframe>
        </div>
    </div>

    <script>
        async function initApp() {
            const tid = "{{ .tid }}";
            const dirResponse = await fetch(`/tasks/dirdata/${tid}`);
            let treeData = await dirResponse.json();
            treeData = JSON.parse(treeData);
            console.log(treeData);

            // 文件缓存系统
            const fileCache = new Map();
            
            // 获取DOM元素
            const previewFrame = document.getElementById('preview-frame');
            const loadingOverlay = document.getElementById('loading');

            // 递归生成目录树
            function createTree(node, parentPath = '') {
                if (node.type === 'file') {
                    const li = document.createElement('li');
                    li.className = 'file';
                    li.textContent = node.name;
                    const fullPath = buildPath(parentPath, node.name);

                    li.addEventListener('click', async (e) => {
                        e.stopPropagation();
                        handleFileClick(fullPath);
                    });

                    // 根据 isTracked 和 CoveredPercent 添加样式类
                    if (node.is_tracked) {
                        if (node.cover_percent >= 70) {
                            li.classList.add('covered-70');
                        } else {
                            li.classList.add('covered-less-70');
                        }
                    }

                    return li;
                }

                if (node.type === 'directory') {
                    const details = document.createElement('details');
                    const summary = document.createElement('summary');
                    summary.className = 'folder';
                    summary.textContent = node.name === '.' ? 'ROOT' : node.name;

                    const ul = document.createElement('ul');
                    ul.style.listStyleType = 'none';
                    ul.style.paddingLeft = '1em';

                    const currentPath = node.name === '.' ? 
                        parentPath : 
                        buildPath(parentPath, node.name);

                    if (node.children) {
                        node.children.forEach(child => {
                            ul.appendChild(createTree(child, currentPath));
                        });
                    }

                    details.appendChild(summary);
                    details.appendChild(ul);

                    // 根据 isTracked 和 CoveredPercent 添加样式类
                    if (node.is_tracked) {
                        if (node.cover_percent >= 70) {
                            summary.classList.add('covered-70');
                        } else {
                            summary.classList.add('covered-less-70');
                        }
                    }

                    return details;
                }

                return document.createDocumentFragment();
            }

            // 路径构建工具函数
            function buildPath(parent, name) {
                return [parent, name]
                    .filter(Boolean)
                    .join('/')
                    .replace(/\/+/g, '/');
            }

            // 文件点击处理
            async function handleFileClick(path) {
                // 显示加载提示
                loadingOverlay.style.display = 'flex';

                try {
                    let content;
                    
                    // 检查缓存
                    if (fileCache.has(path)) {
                        content = fileCache.get(path);
                        previewFrame.removeAttribute('srcdoc');
                    } else {
                        // 真实请求示例（需要配置CORS）
                        const response = await fetch(`/tasks/file?path=${encodeURIComponent(path)}&tid=${tid}`);
                        if (!response.ok) throw new Error(await response.text());
                        content = await response.text();
                        
                        // 缓存结果（可根据需要设置过期时间）
                        fileCache.set(path, content);
                    }

                    // 通过Blob解决同源策略问题
                    const blob = new Blob([content], {type: 'text/html'});
                    const url = URL.createObjectURL(blob);
                    previewFrame.src = url;

                } catch (error) {
                    console.error('加载失败:', error);
                    previewFrame.srcdoc = `
                        <html>
                            <body style="padding: 20px; color: #dc3545;">
                                <h2>加载失败</h2>
                                <pre>${error.message}</pre>
                            </body>
                        </html>
                        `;
                } finally {
                    loadingOverlay.style.display = 'none';
                }
            }

            // 初始化渲染
            function init() {
                const container = document.getElementById('tree-container');
                if (typeof treeData !== 'object' || treeData === null) {
                    container.innerHTML = '<div style="color: red;">数据格式错误</div>';
                    return;
                }
                const nodesArray = [treeData];
                nodesArray.forEach(node => {
                    container.appendChild(createTree(node));
                });
            }

            // 启动应用
            init();
        }

        // 调用异步初始化函数
        initApp().catch(error => {
            console.error('初始化出错:', error);
        });
    </script>
</body>
</html>
{{end}}    
